//
//  EFAAlarmVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/9/8.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAAlarmVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAMaintenanceTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "KSPhotoBrowser.h"
#import "EFAAlarmDevListVC.h"

@interface EFAAlarmVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAMaintenanceTCellDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *alarmBarBtnItem;
@property (nonatomic, strong) EFAAlarmRcdListModel *rcdModel;
@end

static NSString *const kReuseCellId = @"EFAMaintenanceTCell";
static NSInteger const kRequestSize = 20;

@implementation EFAAlarmVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.msg_id ? @"维护记录详情" : @"报警处理";
    //屏蔽此功能，把入口放在设备聊天界面  
//    if (!self.msg_id) {
//        self.navigationItem.rightBarButtonItem = self.alarmBarBtnItem;
//    }
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有维护记录" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.rcdModel.alarmrecord_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAMaintenanceTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.rcdModel.alarmrecord_list.count) {
        [cell configViewWithAlarmListItem:self.rcdModel.alarmrecord_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 9.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    if (indexPath.section < self.noticeModel.announcement_list.count) {
    //        EFANotListItem *item = self.noticeModel.announcement_list[indexPath.section];
    //        [self jumpToNoticeDetailWitNotItem:item indexPath:indexPath];
    //    }
}
#pragma mark - EFAMaintenanceTCellDelegate
- (void)maintenanceTCell:(EFAMaintenanceTCell *)cell imgViewTapped:(NSArray<UIImageView *> *)imgViewArray indexPath:(NSIndexPath *)cIndexPath {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row >= self.rcdModel.alarmrecord_list.count) {
        return;
    }
    EFAAlarmListItem *item = self.rcdModel.alarmrecord_list[indexPath.row];
    if (cIndexPath.row >= item.efairyalarmrecord_imgurl_list.count) {
        return;
    }
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:item.efairyalarmrecord_imgurl_list.count];
    [item.efairyalarmrecord_imgurl_list enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *tempImgView = nil;
        if (idx < imgViewArray.count) {
            tempImgView = imgViewArray[idx];
        }
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:tempImgView imageUrl:[NSURL URLWithString:obj]];
        [mArray addObject:photoItem];
    }];
    [self showPhotoBrowser:mArray selectedIndex:cIndexPath.row];
}

#pragma mark - event response
- (void)alarmBarBtnTapped:(UIBarButtonItem *)item {
    EFAAlarmDevListVC *vc = [[EFAAlarmDevListVC alloc] init];
//    vc.device_id = self.device_id;
//    vc.successHandle = ^{
//        [self.tableView.mj_header beginRefreshing];
//    };
    [self showViewController:vc sender:nil];
}
#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

- (void)jumpToNoticeDetailWitNotItem:(EFANotListItem *)item indexPath:(NSIndexPath *)indexPath {
    //    EFANoticeDetailVC *vc = [[EFANoticeDetailVC alloc] init];
    //    vc.noticeItem = item;
    //    vc.successDelHandle = ^{
    //        [self.noticeModel removeNotListItem:item];
    //        [self refreshWholeView];
    //    };
    //    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.rcdModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.rcdModel.totalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    if (self.msg_id) {
        [self requestAlarmRcdDetail];
    } else {
        [self requestPjtDeviceListWithHeader:isHeader];
    }
}

- (EFAAlarmRcdListModel *)rcdModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.rcdModel;
    }
    
    EFAAlarmRcdListModel *temp = [EFAAlarmRcdListModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.rcdModel;
    }
    
    if (AddMore && self.rcdModel) {
        [self.rcdModel addMoreWithData:temp];
    } else {
        self.rcdModel = temp;
    }
    return self.rcdModel;
}

#pragma mark - network request
- (void)requestPjtDeviceListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.rcdModel.alarmrecord_list.lastObject.efairyalarmrecord_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           //                           @"keyword" : @"",
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiAlarmRcdList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求维护记录列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self rcdModelWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求维护记录列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestAlarmRcdDetail {
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevicemsg_id" : @(self.msg_id)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiAlarmRecord] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求维护记录详情返回：%@", responseObject);
        [self tableViewEndRefresh:YES];
        EFAAlarmListItem *item = [EFAAlarmListItem yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        self.rcdModel = [[EFAAlarmRcdListModel alloc] initWithAlarmListItem:item];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求维护记录详情失败：%@", error);
        [self tableViewEndRefresh:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)alarmBarBtnItem {
    if (!_alarmBarBtnItem) {
        UIImage *img = [[UIImage imageNamed:@"app_alarm_red"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        _alarmBarBtnItem = [[UIBarButtonItem alloc] initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(alarmBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_alarmBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    }
    return _alarmBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
